package com.brillilab.service.core.kit.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.brillilab.dao.mapper.kit.SampleTemplateGroupMapper;
import com.brillilab.dao.mapper.kit.SampleTemplateHideMapper;
import com.brillilab.dao.mapper.kit.SampleTemplateMapper;
import com.brillilab.domain.enums.common.BoolEnum;
import com.brillilab.domain.enums.common.IsDeleteEnum;
import com.brillilab.domain.po.kit.SampleTemplate;
import com.brillilab.domain.po.kit.SampleTemplateGroup;
import com.brillilab.domain.po.kit.SampleTemplateHide;
import com.brillilab.domain.vo.kit.SampleTemplateGroupVo;
import com.brillilab.service.core.kit.ISampleTemplateService;

@Service
@Transactional
public class SampleTemplateServiceImpl implements ISampleTemplateService {

	@Autowired
	private SampleTemplateGroupMapper sampleTemplateGroupMapper;
	@Autowired
	private SampleTemplateMapper sampleTemplateMapper;
	@Autowired
	private SampleTemplateHideMapper sampleTemplateHideMapper;

	@Override
	public SampleTemplate insert(SampleTemplate entity) {
		Assert.isTrue(entity.getGroupId() != null && entity.getReagentTypeId() != null
				&& StringUtils.isNotBlank(entity.getAttrName()), "模版信息不全");
		if ((entity.getInputType() == 2 || entity.getInputType() == 3)
				&& StringUtils.isNotBlank(entity.getJsonData())) {
			JSONObject jsonObj = JSONObject.parseObject(entity.getJsonData());
			JSONArray jsonArray = jsonObj.getJSONArray("data");
			jsonArray.add(0, "");
			jsonObj.put("data", jsonArray);
			entity.setJsonData(jsonObj.toJSONString());
		}
		Integer insert = sampleTemplateMapper.insert(entity);
		Assert.isTrue(insert == 1, "添加失败");
		return entity;
	}

	@Override
	public boolean deleteById(Long id) {
		SampleTemplate sampleTemplate = new SampleTemplate();
		sampleTemplate.setId(id);
		sampleTemplate.setIsDelete(IsDeleteEnum.YES.getValue());
		Integer b = sampleTemplateMapper.updateById(sampleTemplate);
		return b == 1 ? true : false;
	}

	@Override
	public boolean updateById(SampleTemplate sampleTemplate) {
		sampleTemplate.setUpdateTime(new Date());
		Integer b = sampleTemplateMapper.updateById(sampleTemplate);
		return b == 1 ? true : false;
	}

	@Override
	public SampleTemplate selectById(Long id) {
		return sampleTemplateMapper.selectById(id);
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<SampleTemplateGroupVo> getSampleTemplateGroup(Long reagentTypeId, Long labId, Long labMemberId) {
		List<SampleTemplateGroupVo> voList = new ArrayList<>();
		LambdaQueryWrapper<SampleTemplateGroup> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(SampleTemplateGroup::getReagentTypeId, reagentTypeId);
		wrapper.orderByAsc(SampleTemplateGroup::getGroupSort);
		List<SampleTemplateGroup> groupList = sampleTemplateGroupMapper.selectList(wrapper);

		if (groupList != null && groupList.size() > 0) {
			List<SampleTemplate> templateList = new ArrayList<SampleTemplate>();
			if (labId == null) {
				templateList = sampleTemplateMapper.selectSystemList(reagentTypeId);
			} else {
				templateList = sampleTemplateMapper.selectList(reagentTypeId, labId, labMemberId);
			}
			if (templateList != null) {
				Map<Long, List<SampleTemplate>> map = templateList.stream()
						.collect(Collectors.groupingBy(SampleTemplate::getGroupId));
				groupList.forEach(group -> {
					SampleTemplateGroupVo groupVo = new SampleTemplateGroupVo();
					groupVo.setGroupName(group.getGroupName());
					groupVo.setGroupId(group.getId());
					List<SampleTemplate> list = map.get(group.getId());
					groupVo.setTemplateList(list);
					if (!CollectionUtils.isEmpty(list)) {
						Map<Integer, List<SampleTemplate>> map2 = list.stream()
								.collect(Collectors.groupingBy(SampleTemplate::getIsHide));
						List<SampleTemplate> list2 = map2.get(BoolEnum.FALSE.getValue());
						groupVo.setIsHide(CollectionUtils.isEmpty(list2) && !"基础属性".equals(groupVo.getGroupName()) ? BoolEnum.TRUE.getValue() : BoolEnum.FALSE.getValue());
					} else if(!"基础属性".equals(groupVo.getGroupName())){
						groupVo.setIsHide(BoolEnum.TRUE.getValue());
					}
					voList.add(groupVo);
				});
			}
		}
		return voList;
	}

	@Override
	public boolean isHideTemplate(SampleTemplate template, Long labMemberId) {
		LambdaQueryWrapper<SampleTemplateHide> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(SampleTemplateHide::getSampleTemplateId, template.getId());
		wrapper.eq(SampleTemplateHide::getLabId, template.getLabId());
		wrapper.eq(SampleTemplateHide::getLabMemberId, labMemberId);
		SampleTemplateHide templateHide = sampleTemplateHideMapper.selectOne(wrapper);
		if (template.getIsHide() == BoolEnum.TRUE.getValue()) {// 隐藏
			if (templateHide == null) {
				templateHide = new SampleTemplateHide();
				templateHide.setLabId(template.getLabId());
				templateHide.setLabMemberId(labMemberId);
				templateHide.setIsHide(1);
				templateHide.setSampleTemplateId(template.getId());
				int i = sampleTemplateHideMapper.insert(templateHide);
				return i == 1 ? true : false;
			} else if (templateHide != null && templateHide.getIsHide() == BoolEnum.FALSE.getValue()) {
				templateHide.setIsHide(BoolEnum.TRUE.getValue());
				int i = sampleTemplateHideMapper.updateById(templateHide);
				return i == 1 ? true : false;
			}
		} else {// 显示
			if (template.getIsSystemHide() == BoolEnum.TRUE.getValue()) {
				if (templateHide != null) {
					templateHide.setIsHide(BoolEnum.FALSE.getValue());
					int i = sampleTemplateHideMapper.updateById(templateHide);
					return i == 1 ? true : false;
				} else {
					templateHide = new SampleTemplateHide();
					templateHide.setLabId(template.getLabId());
					templateHide.setLabMemberId(labMemberId);
					templateHide.setIsHide(BoolEnum.FALSE.getValue());
					templateHide.setSampleTemplateId(template.getId());
					int i = sampleTemplateHideMapper.insert(templateHide);
					return i == 1 ? true : false;
				}
			} else {
				if (templateHide != null) {
					int i = sampleTemplateHideMapper.deleteById(templateHide.getId());
					return i == 1 ? true : false;
				}
			}

		}
		return true;
	}

	@Override
	public Map<Long, SampleTemplate> getTempMap(Long reagentTypeId, Long labId) {
		Map<Long, SampleTemplate> map = new HashMap<Long, SampleTemplate>();
		List<SampleTemplate> templateList = sampleTemplateMapper.selectList(reagentTypeId, labId, null);
		if(!CollectionUtils.isEmpty(templateList)) {
			templateList.forEach(template ->{
				map.put(template.getId(), template);
			});
		}
		return map;
	}

	@Override
	public boolean addGroup(Long labId, Long reagentTypeId, Long labMemberId) {
		Assert.isTrue(labId != null && reagentTypeId != null, "参数错误");

		LambdaQueryWrapper<SampleTemplateGroup> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(SampleTemplateGroup::getReagentTypeId, reagentTypeId);
		List<SampleTemplateGroup> groupList = sampleTemplateGroupMapper.selectList(wrapper);
		Assert.isTrue(groupList == null || groupList.size() == 0, "样品属性模版组已存在");

		SampleTemplateGroup group1 = new SampleTemplateGroup();
		group1.setReagentTypeId(reagentTypeId);
		group1.setGroupName("基础属性");
		group1.setGroupSort(1);
		int group1Insert = sampleTemplateGroupMapper.insert(group1);
		Assert.isTrue(group1Insert == 1, "添加失败");
		SampleTemplate template = new SampleTemplate();
		template.setLabId(labId);
		template.setReagentTypeId(reagentTypeId);
		template.setLabMemberId(labMemberId);
		template.setGroupId(group1.getId());
		template.setAttrName("编号");
		template.setAttrSort(1);
		template.setInputType(5);
		template.setIsSystem(1);
		this.insert(template);

		template.setId(null);
		template.setAttrName("物种");
		template.setAttrSort(2);
		template.setInputType(3);
		template.setIsSystem(1);
		template.setJsonData(
				"{\"data\":[\"Human(人)\",\"Mouse(小鼠)\",\"Rat(大鼠)\",\"Rabbit(兔)\",\"Goat(羊)\",\"Guinea pig(豚鼠)\",\"Cow(牛)\",\"Pig(猪)\",\"Hamster(仓鼠)\",\"Monkey(猴)\",\"Zebrafish(斑马鱼)\",\"Drosophila(果蝇)\"]}");
		this.insert(template);

		template.setId(null);
		template.setAttrName("性别");
		template.setAttrSort(3);
		template.setInputType(2);
		template.setIsSystem(1);
		template.setJsonData("{\"data\":[\"男(雄)\",\"女(雌)\",\"未知\"]}");
		this.insert(template);

		template.setId(null);
		template.setAttrName("样品类别");
		template.setAttrSort(4);
		template.setInputType(0);
		template.setIsSystem(1);
		template.setJsonData(null);
		this.insert(template);

		SampleTemplateGroup group2 = new SampleTemplateGroup();
		group2.setReagentTypeId(reagentTypeId);
		group2.setGroupName("更多属性");
		group2.setGroupSort(2);
		int group2Insert = sampleTemplateGroupMapper.insert(group2);
		Assert.isTrue(group2Insert == 1, "添加失败");
		return true;
	}

}
